package pers.cj.pdos.controller.analysis;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import pers.cj.pdos.controller.base.BaseController;
import pers.cj.pdos.controller.entity.ResponseData;
import pers.cj.pdos.controller.entity.ResponseList;
import pers.cj.pdos.entity.BusinessSet;
import pers.cj.pdos.entity.Company;
import pers.cj.pdos.entity.ProfitsReport;
import pers.cj.pdos.entity.SaleAnalysis;
import pers.cj.pdos.excel.saleAnalysis.*;
import pers.cj.pdos.service.*;
import pers.cj.pdos.task.CleanTempExcelTask;
import pers.cj.pdos.utils.DateUtils;
import pers.cj.pdos.utils.FileProperUtil;
import pers.cj.pdos.utils.PdosUtils;
import pers.cj.pdos.utils.Utils;
import pers.cj.pdos.vo.SaleGoodsVo;
import pers.cj.pdos.vo.SalePacketVo;
import pers.cj.pdos.vo.SaleVo;
import pers.cj.pdos.vo.UserVo;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

@Controller
@RequestMapping("/goodsCount")
public class SaleAnalysisController extends BaseController {
    @Autowired
    ISaleAnalysisService saleAnalysisService;
    @Autowired
    IStoreService storeService;
    @Autowired
    IHouseService houseService;
    @Autowired
    IGoodsService goodsService;
    @Autowired
    ICustomService customService;
    @Autowired
    ISaleService saleService;
    @Autowired
    IMoneyWaterService moneyWaterService;


    @RequiresPermissions("saleAnalysis:query")
    @RequestMapping("/saleAnalysis")
    public String saleAnalysis(Model model, String storeId, String date1, String date2) {
        model.addAttribute("storeId",storeId);
        model.addAttribute("date1",date1);
        model.addAttribute("date2",date2);
        return "analysis/sale/saleAnalysis";
    }

    @RequiresPermissions("saleAnalysis:query")
    @RequestMapping("/saleAnalysisDetailGoods")
    public String saleAnalysisDetailGoods(Model model, String goodsId,String storeId,String houseId, String date1, String date2) {
        model.addAttribute("goodsId",goodsId);
        model.addAttribute("storeId",storeId);
        model.addAttribute("houseId",houseId);
        model.addAttribute("date1",date1);
        model.addAttribute("date2",date2);

        model.addAttribute("goodsVo",  goodsService.getVoById(goodsId));

        if (!Utils.isEmpty(storeId)) {
            model.addAttribute("storeName",storeService.getById(storeId).getName());
        }

        if (!Utils.isEmpty(houseId)) {
            model.addAttribute("houseName",houseService.getById(houseId).getName());
        }

        return "analysis/sale/saleAnalysisDetailGoods";
    }

    @RequiresPermissions("saleAnalysis:query")
    @RequestMapping("/saleAnalysisDetailCustom")
    public String saleAnalysisDetailCustom(Model model, String customId,String storeId,String houseId, String date1, String date2) {
        model.addAttribute("customId",customId);
        model.addAttribute("storeId",storeId);
        model.addAttribute("houseId",houseId);
        model.addAttribute("date1",date1);
        model.addAttribute("date2",date2);

        model.addAttribute("custom",  customService.getById(customId));

        if (!Utils.isEmpty(storeId)) {
            model.addAttribute("storeName",storeService.getById(storeId).getName());
        }

        if (!Utils.isEmpty(houseId)) {
            model.addAttribute("houseName",houseService.getById(houseId).getName());
        }

        return "analysis/sale/saleAnalysisDetailCustom";
    }

    @RequiresPermissions("saleAnalysis:query")
    @RequestMapping("/saleAnalysisDetailOrder")
    public String saleAnalysisDetailOrder(Model model, String storeId,String houseId, String date) {
        model.addAttribute("date",date);
        model.addAttribute("storeId",storeId);
        model.addAttribute("houseId",houseId);

        if (!Utils.isEmpty(storeId)) {
            model.addAttribute("storeName",storeService.getById(storeId).getName());
        }

        if (!Utils.isEmpty(houseId)) {
            model.addAttribute("houseName",houseService.getById(houseId).getName());
        }

        return "analysis/sale/saleAnalysisDetailOrder";
    }


    @ResponseBody
    @RequestMapping("/saleAnalysis/getAllTotalData")
    public ResponseData getAllTotalData(String storeId,
                                        String houseId,
                                        String date1,
                                        String date2) {
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();
        Map map = saleAnalysisService.getTotalData(company.getId(), PdosUtils.getViewOtherStoreId(userVo,storeId), houseId, Utils.genDate(date1), Utils.genDate(date2));

        Map highGoods = saleAnalysisService.getHighGoods(company.getId(), PdosUtils.getViewOtherStoreId(userVo,storeId), houseId, Utils.genDate(date1), Utils.genDate(date2));
        Map highCustom = saleAnalysisService.getHighCustom(company.getId(), PdosUtils.getViewOtherStoreId(userVo,storeId), houseId, Utils.genDate(date1), Utils.genDate(date2));

        map.put("highGoods", highGoods);
        map.put("highCustom", highCustom);
        return ResponseData.success(map);
    }

    /**
     * 获得今日环比昨日数据
     * @param day
     * @return
     */
    @ResponseBody
    @RequestMapping("/saleAnalysis/getTotalRatioData")
    public ResponseData getTotalRatioData(String day) {
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();

        Map todaySaleTotalMap = saleAnalysisService.getTotalData(company.getId(), PdosUtils.getViewOtherStoreId(userVo,null), null, Utils.genDate(day), Utils.genDate(day));
        BigDecimal todayAmt = moneyWaterService.getTotalAmount(company.getId(), PdosUtils.getViewOtherStoreId(userVo,null), null, Utils.genDate(day), Utils.genDate(day));

        //获取今日的前一天
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(Utils.genDate(day));
        calendar.add(Calendar.DATE, -1);
        String lastDay = DateUtils.getDate(calendar.getTime(), DateUtils.YYYY_MM_DD);
        Map lastDaySaleTotalMap = saleAnalysisService.getTotalData(company.getId(), null, null, Utils.genDate(lastDay), Utils.genDate(lastDay));
        BigDecimal lastDayAmt = moneyWaterService.getTotalAmount(company.getId(),PdosUtils.getViewOtherStoreId(userVo,null), null, Utils.genDate(lastDay), Utils.genDate(lastDay));

        Map map = new HashMap();
        map.put("saleNum", todaySaleTotalMap.get("total_sale_number"));
        map.put("numRatio", PdosUtils.calcChainRatio( PdosUtils.genValueFromMap(todaySaleTotalMap,"total_sale_number"), PdosUtils.genValueFromMap(lastDaySaleTotalMap,"total_sale_number")));
        map.put("saleAmt", todaySaleTotalMap.get("total_sale_amt"));
        map.put("amtRatio", PdosUtils.calcChainRatio( PdosUtils.genValueFromMap(todaySaleTotalMap,"total_sale_amt"), PdosUtils.genValueFromMap(lastDaySaleTotalMap,"total_sale_amt")));
        map.put("profits", todaySaleTotalMap.get("total_sale_profits"));
        map.put("profitsRatio", PdosUtils.calcChainRatio( PdosUtils.genValueFromMap(todaySaleTotalMap,"total_sale_profits"), PdosUtils.genValueFromMap(lastDaySaleTotalMap,"total_sale_profits")));
        map.put("inAmt", todayAmt);
        map.put("inRatio", PdosUtils.calcChainRatio(todayAmt, lastDayAmt));
        return ResponseData.success(map);
    }


    @ResponseBody
    @RequestMapping("/saleAnalysis/listStoreData")
    public ResponseList listStoreData(String storeId,
                                      String houseId,
                                      String date1,
                                      String date2) {
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();
        List<SaleAnalysis> list = saleAnalysisService.listStoreData(company.getId(),
                null,
                null,
                PdosUtils.getViewOtherStoreId(userVo,storeId),
                houseId,
                Utils.genDate(date1),
                Utils.genDate(date2));

        return ResponseList.success(list.size(), list);
    }

    @ResponseBody
    @RequestMapping("/saleAnalysis/listHouseData")
    public ResponseList listHouseData(String storeId,
                                      String houseId,
                                      String date1,
                                      String date2) {
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();
        List<SaleAnalysis> list = saleAnalysisService.listHouseData(company.getId(),
                null,
                null,
                PdosUtils.getViewOtherStoreId(userVo,storeId),
                houseId,
                Utils.genDate(date1),
                Utils.genDate(date2));

        return ResponseList.success(list.size(), list);
    }

    @ResponseBody
    @RequestMapping("/saleAnalysis/listGoodsData")
    public ResponseList listGoodsData(String page,
                                      String limit,
                                      String storeId,
                                      String houseId,
                                      String customId,
                                      String userId,
                                      String date1,
                                      String date2,
                                      String typeId,
                                      String filterZero,
                                      String search) {
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();
        List<SaleAnalysis> list = saleAnalysisService.listGoodsData(company.getId(),
                Utils.genInteger(page),
                Utils.genInteger(limit),
                PdosUtils.getViewOtherStoreId(userVo,storeId),
                houseId,
                customId,
                userId,
                Utils.genDate(date1),
                Utils.genDate(date2),
                typeId,
                Utils.genBoolean(filterZero),
                Utils.genLikeData(search));

        Long count = saleAnalysisService.countGoodsData(company.getId(),
                PdosUtils.getViewOtherStoreId(userVo,storeId),
                houseId,
                customId,
                userId,
                Utils.genDate(date1),
                Utils.genDate(date2),
                typeId,
                Utils.genBoolean(filterZero),
                Utils.genLikeData(search));

        return ResponseList.success(count, list);
    }

    @ResponseBody
    @RequestMapping("/saleAnalysis/listCustomData")
    public ResponseList listCustomData(String page,
                                      String limit,
                                      String storeId,
                                      String houseId,
                                      String date1,
                                      String date2,
                                      String customTypeId,
                                      String filterZero,
                                      String search) {
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();
        List<SaleAnalysis> list = saleAnalysisService.listCustomData(company.getId(),
                Utils.genInteger(page),
                Utils.genInteger(limit),
                PdosUtils.getViewOtherStoreId(userVo,storeId),
                houseId,
                Utils.genDate(date1),
                Utils.genDate(date2),
                customTypeId,
                Utils.genBoolean(filterZero),
                Utils.genLikeData(search));

        Long count = saleAnalysisService.countCustomData(company.getId(),
                PdosUtils.getViewOtherStoreId(userVo,storeId),
                houseId,
                Utils.genDate(date1),
                Utils.genDate(date2),
                customTypeId,
                Utils.genBoolean(filterZero),
                Utils.genLikeData(search));

        return ResponseList.success(count, list);
    }

    @ResponseBody
    @RequestMapping("/saleAnalysis/listOrderData")
    public ResponseList listOrderData(String page,
                                     String limit,
                                     String storeId,
                                     String houseId,
                                     String date1,
                                     String date2) {
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();
        List<SaleAnalysis> list = saleAnalysisService.listOrderData(company.getId(),
                Utils.genInteger(page),
                Utils.genInteger(limit),
                PdosUtils.getViewOtherStoreId(userVo,storeId),
                houseId,
                Utils.genDate(date1),
                Utils.genDate(date2));

        Long count = saleAnalysisService.countOrderData(company.getId(),
                PdosUtils.getViewOtherStoreId(userVo,storeId),
                houseId,
                Utils.genDate(date1),
                Utils.genDate(date2));

        return ResponseList.success(count, list);
    }

    @ResponseBody
    @RequestMapping("/saleAnalysis/getOrderDetail")
    public ResponseList getOrderDetail(int page,
                                int limit,
                                String close,
                                String search,
                                String no,
                                String goodsName,
                                String remark,
                                String storeId,
                                String houseId,
                                String settAccountId,
                                String custom,
                                String deliveryDate1,
                                String deliveryDate2,
                                String makeTime1,
                                String makeTime2,
                                String userId,
                                String date1,
                                String date2,
                                String date,
                                String makeUserId,
                                String customId,
                                String status){
        Company company = getCompany();

        UserVo userVo = getLoginUserVo();
        List<SaleVo> saleVoList = saleService.listVo(company.getId(),
                page,
                limit,
                Utils.genBoolean(close),
                Utils.genLikeData(search),
                Utils.genLikeData(no),
                Utils.genLikeData(goodsName),
                Utils.genLikeData(remark),
                PdosUtils.getViewOtherStoreId(userVo,storeId),
                houseId,
                settAccountId,
                Utils.genLikeData(custom),
                Utils.genDate(deliveryDate1),
                Utils.genDate(deliveryDate2),
                Utils.genDate(makeTime1),
                Utils.genDate(makeTime2),
                null,
                userId,
                Utils.genDate(date1),
                Utils.genDate(date2),
                Utils.genDate(date),
                makeUserId,
                customId,
                Utils.genInteger(status));
        long count = saleService.count(company.getId(),
                Utils.genBoolean(close),
                Utils.genLikeData(search),
                Utils.genLikeData(no),
                Utils.genLikeData(goodsName),
                Utils.genLikeData(remark),
                PdosUtils.getViewOtherStoreId(userVo,storeId),
                houseId,
                settAccountId,
                Utils.genLikeData(custom),
                Utils.genDate(deliveryDate1),
                Utils.genDate(deliveryDate2),
                Utils.genDate(makeTime1),
                Utils.genDate(makeTime2),
                null,
                userId,
                Utils.genDate(date1),
                Utils.genDate(date2),
                Utils.genDate(date),
                makeUserId,
                customId,
                Utils.genInteger(status));
        return ResponseList.success(count,saleVoList);
    }


    @ResponseBody
    @RequestMapping("/saleAnalysis/listGoodsDetailDataByOrder")
    public ResponseList listGoodsDetailDataByOrder(String goodsId,
                                            String page,
                                            String limit,
                                            String storeId,
                                            String houseId,
                                            String date1,
                                            String date2,
                                            String search) {
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();
        List<SaleAnalysis> list = saleAnalysisService.listGoodsDetailDataByOrder(company.getId(),
                goodsId,
                Utils.genInteger(page),
                Utils.genInteger(limit),
                PdosUtils.getViewOtherStoreId(userVo,storeId),
                houseId,
                Utils.genDate(date1),
                Utils.genDate(date2),
                Utils.genLikeData(search));

        Long count = saleAnalysisService.countGoodsDetailDataByOrder(company.getId(),
                goodsId,
                PdosUtils.getViewOtherStoreId(userVo,storeId),
                houseId,
                Utils.genDate(date1),
                Utils.genDate(date2),
                Utils.genLikeData(search));

        return ResponseList.success(count, list);
    }

    @ResponseBody
    @RequestMapping("/saleAnalysis/listGoodsDetailDataByCustom")
    public ResponseList listGoodsDetailDataByCustom(String goodsId,
                                                   String page,
                                                   String limit,
                                                   String storeId,
                                                   String houseId,
                                                   String date1,
                                                   String date2,
                                                   String search) {
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();
        List<SaleAnalysis> list = saleAnalysisService.listGoodsDetailDataByCustom(company.getId(),
                goodsId,
                Utils.genInteger(page),
                Utils.genInteger(limit),
                PdosUtils.getViewOtherStoreId(userVo,storeId),
                houseId,
                Utils.genDate(date1),
                Utils.genDate(date2),
                Utils.genLikeData(search));

        Long count = saleAnalysisService.countGoodsDetailDataByCustom(company.getId(),
                goodsId,
                PdosUtils.getViewOtherStoreId(userVo,storeId),
                houseId,
                Utils.genDate(date1),
                Utils.genDate(date2),
                Utils.genLikeData(search));

        return ResponseList.success(count, list);
    }

    @ResponseBody
    @RequestMapping("/saleAnalysis/chatDetailData")
    public ResponseData chatDetailData(String goodsId,
                                       String customId,
                                       String storeId,
                                       String houseId,
                                       String userId,
                                       String date1,
                                       String date2) {
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();
        BusinessSet businessSet = getBusinessSet();
        if (Utils.isEmpty(date1) || Utils.isEmpty(date2)) {
            //则日期需要根据数据库出来的数据做判断
            Map map = saleAnalysisService.getMaxMinDate(company.getId(), goodsId, customId, PdosUtils.getViewOtherStoreId(userVo,storeId),houseId);
            if (map == null) {
                //说明数据库无数据
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(new Date());
                date2 = DateUtils.getDate(calendar.getTime(), DateUtils.YYYY_MM_DD);
                calendar.add(Calendar.DATE, -6);
                date1 = DateUtils.getDate(calendar.getTime(), DateUtils.YYYY_MM_DD);
            } else {
                date1 = DateUtils.getDate((Date)map.get("minDate"), DateUtils.YYYY_MM_DD);
                date2 = DateUtils.getDate((Date)map.get("maxDate"), DateUtils.YYYY_MM_DD);
            }
        }

        int flag = PdosUtils.calcDateDiffFlag(date1,date2);
        if (flag == -1) {
            return ResponseData.success(null);
        }

        Map<String, Object> chatMap = PdosUtils.calcDateDiffMap(date1,date2, businessSet);
        if (flag == 1) {
            //按照年份获取总销售额
            List<Map> mapList = saleAnalysisService.getTotalByYear(company.getId(),goodsId, customId, userId,PdosUtils.getViewOtherStoreId(userVo,storeId),houseId, Utils.genDate(date1), Utils.genDate(date2));
            for (Map map : mapList) {

                chatMap.put(map.get("year")+"年", PdosUtils.getPrice((BigDecimal) map.get("amount"),businessSet));
            }
        } else if (flag == 2) {
            //按照月获取总销售额
            List<Map> mapList = saleAnalysisService.getTotalByMonth(company.getId(),goodsId, customId, userId,PdosUtils.getViewOtherStoreId(userVo,storeId),houseId, Utils.genDate(date1), Utils.genDate(date2));
            for (Map map : mapList) {
                chatMap.put(map.get("month")+"月", PdosUtils.getPrice((BigDecimal) map.get("amount"),businessSet));
            }
        } else if (flag == 3) {
            //按照日获取总销售额
            List<Map> mapList = saleAnalysisService.getTotalByDate(company.getId(),goodsId, customId, userId,PdosUtils.getViewOtherStoreId(userVo,storeId),houseId, Utils.genDate(date1), Utils.genDate(date2));
            for (Map map : mapList) {
                chatMap.put(map.get("date")+"日", PdosUtils.getPrice((BigDecimal) map.get("amount"),businessSet));
            }
        }

        return ResponseData.success(chatMap);
    }




    @ResponseBody
    @RequiresPermissions("saleAnalysis:export")
    @RequestMapping("/saleAnalysis/exportGoodsData")
    public ResponseData exportGoodsData(String fileName,
                                        String storeId,
                                        String houseId,
                                        String customId,
                                        String date1,
                                        String date2,
                                        String typeId,
                                        String filterZero,
                                        String search) {
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();
        BusinessSet businessSet = getBusinessSet();
        List<SaleAnalysis> list = saleAnalysisService.listGoodsData(company.getId(),
                null,
                null,
                PdosUtils.getViewOtherStoreId(userVo,storeId),
                houseId,
                customId,
                null,
                Utils.genDate(date1),
                Utils.genDate(date2),
                typeId,
                Utils.genBoolean(filterZero),
                Utils.genLikeData(search));

        List<ExcelSaleAnalysisGoods> excelList = new ArrayList<>();
        for (SaleAnalysis entity : list) {
            ExcelSaleAnalysisGoods excel = new ExcelSaleAnalysisGoods();
            excel.setNo(entity.getNo());
            excel.setName(entity.getName());
            excel.setNorms(entity.getNorms());
            excel.setUnitName(entity.getUnitName());
            excel.setNumber(PdosUtils.getNumber(entity.getNumber(), businessSet));
            excel.setAmount(PdosUtils.getPrice(entity.getAmount(), businessSet));
            excel.setAvgAmount(PdosUtils.getPrice(entity.getAvgAmount(), businessSet));
            excel.setProfits(PdosUtils.getPrice(entity.getProfits(), businessSet));
            excel.setTax(PdosUtils.getPrice(entity.getTax(), businessSet));
            excelList.add(excel);
        }


        String excelName = fileName + DateUtils.getDate(new Date(), DateUtils.YYYYMMDDHHMMSSSS) + ".xlsx";

        try {
            String path = FileProperUtil.getInstance().getVal("excel.temp");
            OutputStream out = new FileOutputStream(path + excelName);
            ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, true);
            Sheet sheet1 = new Sheet(1, 0, ExcelSaleAnalysisGoods.class);
            sheet1.setSheetName(fileName + "信息");
            writer.write(excelList, sheet1);
            writer.finish();
            out.close();
            CleanTempExcelTask.put(excelName, new Date().getTime());
            return ResponseData.success(excelName);
        } catch (IOException e) {
            return ResponseData.fail("导出失败");
        }
    }

    @ResponseBody
    @RequiresPermissions("saleAnalysis:export")
    @RequestMapping("/saleAnalysis/exportCustomData")
    public ResponseData exportCustomData(String fileName,
                                         String storeId,
                                         String houseId,
                                         String date1,
                                         String date2,
                                         String customTypeId,
                                         String filterZero,
                                         String search) {
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();
        BusinessSet businessSet = getBusinessSet();
        List<SaleAnalysis> list = saleAnalysisService.listCustomData(company.getId(),
                null,
                null,
                PdosUtils.getViewOtherStoreId(userVo,storeId),
                houseId,
                Utils.genDate(date1),
                Utils.genDate(date2),
                customTypeId,
                Utils.genBoolean(filterZero),
                Utils.genLikeData(search));

        List<ExcelSaleAnalysisCustom> excelList = new ArrayList<>();
        for (SaleAnalysis entity : list) {
            ExcelSaleAnalysisCustom excel = new ExcelSaleAnalysisCustom();
            excel.setNo(entity.getNo());
            excel.setName(entity.getName());
            excel.setNumber(PdosUtils.getNumber(entity.getNumber(), businessSet));
            excel.setAmount(PdosUtils.getPrice(entity.getAmount(), businessSet));
            excel.setRatio(PdosUtils.getNumber(entity.getRatio(), businessSet)+"%");
            excel.setProfits(PdosUtils.getPrice(entity.getProfits(), businessSet));
            excel.setDiscountAmt(PdosUtils.getPrice(entity.getDiscountAmt(), businessSet));
            excel.setTax(PdosUtils.getPrice(entity.getTax(), businessSet));
            excelList.add(excel);
        }

        String excelName = fileName + DateUtils.getDate(new Date(), DateUtils.YYYYMMDDHHMMSSSS) + ".xlsx";
        try {
            String path = FileProperUtil.getInstance().getVal("excel.temp");
            OutputStream out = new FileOutputStream(path + excelName);
            ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, true);
            Sheet sheet1 = new Sheet(1, 0, ExcelSaleAnalysisCustom.class);
            sheet1.setSheetName(fileName + "信息");
            writer.write(excelList, sheet1);
            writer.finish();
            out.close();
            CleanTempExcelTask.put(excelName, new Date().getTime());
            return ResponseData.success(excelName);
        } catch (IOException e) {
            return ResponseData.fail("导出失败");
        }
    }

    @ResponseBody
    @RequiresPermissions("saleAnalysis:export")
    @RequestMapping("/saleAnalysis/exportOrderData")
    public ResponseData exportOrderData(String fileName,
                                        String storeId,
                                        String houseId,
                                        String date1,
                                        String date2) {
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();
        BusinessSet businessSet = getBusinessSet();
        List<SaleAnalysis> list = saleAnalysisService.listOrderData(company.getId(),
                null,
                null,
                PdosUtils.getViewOtherStoreId(userVo,storeId),
                houseId,
                Utils.genDate(date1),
                Utils.genDate(date2));

        List<ExcelSaleAnalysisOrder> excelList = new ArrayList<>();
        for (SaleAnalysis entity : list) {
            ExcelSaleAnalysisOrder excel = new ExcelSaleAnalysisOrder();
            excel.setDate(entity.getDate());
            excel.setNumber(PdosUtils.getNumber(entity.getNumber(), businessSet));
            excel.setAmount(PdosUtils.getPrice(entity.getAmount(), businessSet));
            excel.setCost(PdosUtils.getPrice(entity.getCost(), businessSet));
            excel.setProfits(PdosUtils.getPrice(entity.getProfits(), businessSet));
            excel.setTax(PdosUtils.getPrice(entity.getTax(), businessSet));
            excelList.add(excel);
        }

        String excelName = fileName + DateUtils.getDate(new Date(), DateUtils.YYYYMMDDHHMMSSSS) + ".xlsx";
        try {
            String path = FileProperUtil.getInstance().getVal("excel.temp");
            OutputStream out = new FileOutputStream(path + excelName);
            ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, true);
            Sheet sheet1 = new Sheet(1, 0, ExcelSaleAnalysisOrder.class);
            sheet1.setSheetName(fileName+"信息");
            writer.write(excelList, sheet1);
            writer.finish();
            out.close();
            CleanTempExcelTask.put(excelName, new Date().getTime());
            return ResponseData.success(excelName);
        } catch (IOException e) {
            return ResponseData.fail("导出失败");
        }
    }

    @ResponseBody
    @RequiresPermissions("saleAnalysis:export")
    @RequestMapping("/saleAnalysis/exportGoodsDetailDataByOrder")
    public ResponseData exportGoodsDetailDataByOrder(String goodsId,
                                                     String storeId,
                                                     String houseId,
                                                     String date1,
                                                     String date2,
                                                     String search) {
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();
        BusinessSet businessSet = getBusinessSet();
        List<SaleAnalysis> list = saleAnalysisService.listGoodsDetailDataByOrder(company.getId(),
                goodsId,
                null,
                null,
                PdosUtils.getViewOtherStoreId(userVo,storeId),
                houseId,
                Utils.genDate(date1),
                Utils.genDate(date2),
                Utils.genLikeData(search));

        List<ExcelSaleAnalysisGoodsOrder> excelList = new ArrayList<>();
        for (SaleAnalysis entity : list) {
            ExcelSaleAnalysisGoodsOrder excel = new ExcelSaleAnalysisGoodsOrder();
            excel.setDate(entity.getDate());
            excel.setNo(entity.getNo());
            excel.setCustomName(entity.getCustomName());
            excel.setType(entity.getType());
            excel.setUnitName(entity.getUnitName());
            excel.setNumber(PdosUtils.getNumber(entity.getNumber(), businessSet));
            excel.setAmount(PdosUtils.getPrice(entity.getAmount(), businessSet));
            excel.setDiscountAmt(PdosUtils.getPrice(entity.getDiscountAmt(), businessSet));
            excel.setAvgAmount(PdosUtils.getPrice(entity.getAmount().divide(entity.getNumber(),4, RoundingMode.HALF_UP), businessSet));
            excel.setProfits(PdosUtils.getPrice(entity.getProfits(), businessSet));
            excel.setTax(PdosUtils.getPrice(entity.getTax(), businessSet));
            excelList.add(excel);
        }

        String fileName = "销售报表按商品按单据表" + DateUtils.getDate(new Date(), DateUtils.YYYYMMDDHHMMSSSS) + ".xlsx";
        try {
            String path = FileProperUtil.getInstance().getVal("excel.temp");
            OutputStream out = new FileOutputStream(path + fileName);
            ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, true);
            Sheet sheet1 = new Sheet(1, 0, ExcelSaleAnalysisGoodsOrder.class);
            sheet1.setSheetName("销售报表按商品按单据表信息");
            writer.write(excelList, sheet1);
            writer.finish();
            out.close();
            CleanTempExcelTask.put(fileName, new Date().getTime());
            return ResponseData.success(fileName);
        } catch (IOException e) {
            return ResponseData.fail("导出失败");
        }
    }

    @ResponseBody
    @RequiresPermissions("saleAnalysis:export")
    @RequestMapping("/saleAnalysis/exportGoodsDetailDataByCustom")
    public ResponseData exportGoodsDetailDataByCustom(String goodsId,
                                                      String storeId,
                                                      String houseId,
                                                      String date1,
                                                      String date2,
                                                      String search) {
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();
        BusinessSet businessSet = getBusinessSet();
        List<SaleAnalysis> list = saleAnalysisService.listGoodsDetailDataByCustom(company.getId(),
                goodsId,
                null,
                null,
                PdosUtils.getViewOtherStoreId(userVo,storeId),
                houseId,
                Utils.genDate(date1),
                Utils.genDate(date2),
                Utils.genLikeData(search));

        List<ExcelSaleAnalysisGoodsCustom> excelList = new ArrayList<>();
        for (SaleAnalysis entity : list) {
            ExcelSaleAnalysisGoodsCustom excel = new ExcelSaleAnalysisGoodsCustom();
            excel.setName(entity.getName());
            excel.setUnitName(entity.getUnitName());
            excel.setNumber(PdosUtils.getNumber(entity.getNumber(), businessSet));
            excel.setAmount(PdosUtils.getPrice(entity.getAmount(), businessSet));
            excel.setDiscountAmt(PdosUtils.getPrice(entity.getDiscountAmt(), businessSet));
            excel.setAvgAmount(PdosUtils.getPrice(entity.getAmount().divide(entity.getNumber(),4, RoundingMode.HALF_UP), businessSet));
            excel.setProfits(PdosUtils.getPrice(entity.getProfits(), businessSet));
            excel.setTax(PdosUtils.getPrice(entity.getTax(), businessSet));
            excelList.add(excel);
        }

        String fileName = "销售报表按商品按客户表" + DateUtils.getDate(new Date(), DateUtils.YYYYMMDDHHMMSSSS) + ".xlsx";
        try {
            String path = FileProperUtil.getInstance().getVal("excel.temp");
            OutputStream out = new FileOutputStream(path + fileName);
            ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, true);
            Sheet sheet1 = new Sheet(1, 0, ExcelSaleAnalysisGoodsCustom.class);
            sheet1.setSheetName("销售报表按商品按客户表信息");
            writer.write(excelList, sheet1);
            writer.finish();
            out.close();
            CleanTempExcelTask.put(fileName, new Date().getTime());
            return ResponseData.success(fileName);
        } catch (IOException e) {
            return ResponseData.fail("导出失败");
        }
    }

    @ResponseBody
    @RequiresPermissions("saleAnalysis:export")
    @RequestMapping("/saleAnalysis/exportCustomDetailDataByOrder")
    public ResponseData exportCustomDetailDataByOrder(String customId,
                                                      String storeId,
                                                      String houseId,
                                                      String date1,
                                                      String date2,
                                                      String search) {
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();
        BusinessSet businessSet = getBusinessSet();
        List<SaleVo> list = saleService.listVo(company.getId(),
                null,
                null,
                false,
                Utils.genLikeData(search),
                null,
                null,
                null,
                PdosUtils.getViewOtherStoreId(userVo,storeId),
                houseId,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                Utils.genDate(date1),
                Utils.genDate(date2),
                null,
                null,
                customId,
                null);

        List<ExcelSaleAnalysisCustomOrder> excelList = new ArrayList<>();
        for (SaleVo entity : list) {
            ExcelSaleAnalysisCustomOrder excel = new ExcelSaleAnalysisCustomOrder();
            excel.setNo(entity.getNo());
            excel.setDate(DateUtils.getDate(entity.getDate(), DateUtils.YYYY_MM_DD));

            String goods = "";
            if (!Utils.isEmpty(entity.getSaleGoodsVoList())) {
                for (SaleGoodsVo saleGoodsVo : entity.getSaleGoodsVoList()) {
                    goods += saleGoodsVo.getGoodsVo().getName() + "、";
                }
            }

            if (!Utils.isEmpty(entity.getSalePacketVoList())) {
                for (SalePacketVo salePacketVo : entity.getSalePacketVoList()) {
                    goods += salePacketVo.getPacketName() + "、";
                }
            }

            if (!Utils.isEmpty(goods)) {
                goods = goods.substring(0, goods.length() - 1);
            }
            excel.setGoods(goods);
            excel.setAmount(PdosUtils.getPrice(entity.getAfterDiscountAmt(), businessSet));
            excel.setDiscountAmt(PdosUtils.getPrice(entity.getDiscountAmt(), businessSet));
            excel.setProfits(PdosUtils.getPrice(entity.getProfits(), businessSet));
            excel.setTax(PdosUtils.getPrice(entity.getTax(), businessSet));
            excelList.add(excel);
        }

        String fileName = "销售报表按客户按单据表" + DateUtils.getDate(new Date(), DateUtils.YYYYMMDDHHMMSSSS) + ".xlsx";
        try {
            String path = FileProperUtil.getInstance().getVal("excel.temp");
            OutputStream out = new FileOutputStream(path + fileName);
            ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, true);
            Sheet sheet1 = new Sheet(1, 0, ExcelSaleAnalysisCustomOrder.class);
            sheet1.setSheetName("销售报表按客户按单据表信息");
            writer.write(excelList, sheet1);
            writer.finish();
            out.close();
            CleanTempExcelTask.put(fileName, new Date().getTime());
            return ResponseData.success(fileName);
        } catch (IOException e) {
            return ResponseData.fail("导出失败");
        }
    }

    @ResponseBody
    @RequiresPermissions("saleAnalysis:export")
    @RequestMapping("/saleAnalysis/exportOrderDetailData")
    public ResponseData exportOrderDetailData(String date,
                                              String storeId,
                                              String houseId,
                                              String search) {
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();
        BusinessSet businessSet = getBusinessSet();
        List<SaleVo> list = saleService.listVo(company.getId(),
                null,
                null,
                false,
                Utils.genLikeData(search),
                null,
                null,
                null,
                PdosUtils.getViewOtherStoreId(userVo,storeId),
                houseId,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                Utils.genDate(date),
                null,
                null,
                null);

        List<ExcelSaleAnalysisOrderDetail> excelList = new ArrayList<>();
        for (SaleVo entity : list) {
            ExcelSaleAnalysisOrderDetail excel = new ExcelSaleAnalysisOrderDetail();
            excel.setNo(entity.getNo());
            excel.setDate(DateUtils.getDate(entity.getDate(), DateUtils.YYYY_MM_DD));

            String goods = "";
            if (!Utils.isEmpty(entity.getSaleGoodsVoList())) {
                for (SaleGoodsVo saleGoodsVo : entity.getSaleGoodsVoList()) {
                    goods += saleGoodsVo.getGoodsVo().getName() + "、";
                }
            }

            if (!Utils.isEmpty(entity.getSalePacketVoList())) {
                for (SalePacketVo salePacketVo : entity.getSalePacketVoList()) {
                    goods += salePacketVo.getPacketName() + "、";
                }
            }

            if (!Utils.isEmpty(goods)) {
                goods = goods.substring(0, goods.length() - 1);
            }
            excel.setGoods(goods);
            excel.setAmount(PdosUtils.getPrice(entity.getAfterDiscountAmt(), businessSet));
            excel.setCost(PdosUtils.getPrice(entity.getAfterDiscountAmt().subtract(entity.getProfits()), businessSet));
            excel.setProfits(PdosUtils.getPrice(entity.getProfits(), businessSet));
            excel.setOtherAmt(PdosUtils.getPrice(entity.getOtherAmt(), businessSet));
            excel.setTax(PdosUtils.getPrice(entity.getTax(), businessSet));
            excelList.add(excel);
        }

        String fileName = "销售报表按单据详情表" + DateUtils.getDate(new Date(), DateUtils.YYYYMMDDHHMMSSSS) + ".xlsx";
        try {
            String path = FileProperUtil.getInstance().getVal("excel.temp");
            OutputStream out = new FileOutputStream(path + fileName);
            ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, true);
            Sheet sheet1 = new Sheet(1, 0, ExcelSaleAnalysisOrderDetail.class);
            sheet1.setSheetName("销售报表按单据详情表信息");
            writer.write(excelList, sheet1);
            writer.finish();
            out.close();
            CleanTempExcelTask.put(fileName, new Date().getTime());
            return ResponseData.success(fileName);
        } catch (IOException e) {
            return ResponseData.fail("导出失败");
        }
    }
}
